package com.walle.gatewayserver.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.walle.gatewayserver.base.CodeContant;

import java.util.Date;

public class JWTUtil {



    /**
     * 生成签名,5min后过期
     * @param iss jwt签发者
     * @param sub 用户信息
     * @param secret 密钥
     * @param expireTime 有效时间(秒)
     * @return 加密的token
     */
    public static String sign(String iss, String sub, String secret, long expireTime) throws Exception {

        try {

            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            Date expireDate = new Date(nowMillis + expireTime * 1000);
            Algorithm algorithm = Algorithm.HMAC256(secret);

            // 附带username信息
            return JWT.create()
                    .withIssuer(iss)
                    .withIssuedAt(now)
                    .withJWTId(UUIDGenerator.getUUID())
                    .withSubject(sub)
                    .withExpiresAt(expireDate)
                    .sign(algorithm);

        } catch (Exception e) {

            // token生成失败
            throw  new Exception(CodeContant.TOKEN_CREATE_ERROR.getMsg() );
        }
    }

    public static void main(String[] args) {


    }
}
